#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymongo;
from  config import *
from numpy import nan as NA
import pandas as pd
from datetime import datetime
client = pymongo.MongoClient(MONGO_URL);
db = client["douban"];
import matplotlib.pyplot as plot
plot.rcParams['font.sans-serif'] = ['SimHei']
plot.rcParams['font.family']='sans-serif'
def get_data():
    queryArgs = {}
    projectionFields = {'_id': False}  # 用字典指定
    result = db["active_user"].find(queryArgs,projectionFields)
    return result
# 推荐  说   转播   0
#  关注 订阅 活动   1
# 看 |影评  影视    2
# 读 | 阅读  书籍   3
# 日记              4
# 照片              5
# 喜欢  豆列            6


def main():
    douban={}
    data=pd.DataFrame(list(get_data()))
    tags=list(data["tags"])
    for tag in tags:
        for ta in tag:
            type=getTagType(ta)
            if type in douban:
                douban[type]+=1
            else:
                douban[type]=1
    print(douban)
    labels=list(douban.keys())
    fracs=[]
    values=list(douban.values())
    sum=0
    for c in values:
        sum+=c

    for c in values:
        fracs.append(round(c/sum,2))
    print(fracs)

    explode = (0, 0.05, 0, 0,0,0,0,0)
    # Make square figures and axes
    plot.axes(aspect=1)

    plot.title("豆瓣留存用户功能使用分布")
    # plt.pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True)
    plot.pie(fracs, explode=explode, labels=labels, autopct='%.0f%%', shadow=True)
    plot.legend(labels,loc="upper left",bbox_to_anchor=(1,1))
    plot.savefig("douban.png")
    plot.show()






def getTagType(str):

    type="未知"
    if str == "" or str == None:
        return type
    if "推荐" in str or "说"in str or "转播" in str:
        type="广播"
    elif  "关注" in str or "订阅"in str or "活动" in str:
        type="互动"
    elif "看" in str or "影评" in str or  "影视"in str:
        type="影视"
    elif "读" in str or  "阅读"in str or   "书籍" in str:
        type="阅读"
    elif "日记" in str:
        type="日记"
    elif "照片" in str:
        type="照片"
    elif "喜欢" in str or "豆列" in str:
        type="收藏"
    else:
        type="未知"
        print(str)
    return type




def get_active_user_url():
    data=pd.DataFrame(list(get_data()))

    print(data.describe())
    data[data["update_time"]==""]="2012-9-30 9:40:02"

    data=data.dropna(how="any")
    data["update_time"]=data["update_time"].apply(handleTime)
    data=data.sort_values(by="update_time", ascending=False)
    datatime1=datetime(2017,10,8)
    data=data[data["update_time"] > datatime1]
    list_url=list(data["user_url"])
    return list_url




# 1934
def get_active_time(data):
    print(data.head())
    data = data.reindex(index=data["update_time"],columns=["user_name"])
    data["count"]=1
    data=data.drop(["user_name"],axis=1)
    data=data.resample("D").sum().fillna(0).cumsum()

    data["current_count"]=1934
    data["rate"]=1
    data["current_count"]=data["current_count"]-data["count"]
    data["rate"]=data["current_count"]/1934
    data=data[:"2017-10-08"]
    print(data.tail())
    hua_tu(data)




def hua_tu(data):
    plot.title("豆瓣用户流失情况")
    plot.plot(data.index, data["current_count"])
    plot.ylabel("仍然在活跃的用户个数")
    plot.twinx()
    plot.plot(data.index, data["rate"])
    plot.ylabel("当前用户活跃比例")
    plot.savefig("douban.jpg")
    plot.show()


def handleTime(str):
    try:
        time_mode = "%Y-%m-%d %H:%M:%S"
        time = datetime.strptime(str, time_mode)
    except Exception as e:
        print(e)
        print(str)
        return datetime.now()
    return time




if __name__ == '__main__':
    main()